#include "videowidget.h"
#include <QPainter>

VideoWidget::VideoWidget(QWidget *parent) : QWidget(parent)
{

}

VideoWidget::~VideoWidget(){
    freeImage();
}

void VideoWidget::onPlayerFrameDecoded(VideoPlayer *player, uint8_t *data, VideoPlayer::VideoSwsSpec &spec){
    if(player->getState() == VideoPlayer::Stopped) return;
    //释放之前的图片
    freeImage();

    //创建新的图片
    if(data != nullptr){
        m_image = new QImage(data,spec.width,spec.height,QImage::Format_RGB888);
        //计算尺寸
        //组件尺寸
        int w = width();
        int h = height();

        //计算 rect
        int dx = 0;
        int dy = 0;
        int dw = spec.width;
        int dh = spec.height;

        //计算目标尺寸
        if(dw > w || dh > h){
            if(dw * h > w * dh){
                //TODO
                //保持视频原始宽高比，防止失真
                dh = w * dh /dw;
                dw = w;
            }else{
                dw = h * dw/dh;
                dh = h;
            }
        }

        //居中
        dx = (w-dw) >> 1;
        dy = (h-dh) >> 1;

        m_rect = QRect(dx,dy,dw,dh);

    }
    update();
}


void VideoWidget::freeImage(){
    if(m_image){
        av_free(m_image->bits());
        delete m_image;
        m_image = nullptr;
    }
}

void VideoWidget::paintEvent(QPaintEvent* ev){
    if(!m_image) return;
    QPainter(this).drawImage(m_rect,*m_image);
}

void VideoWidget::onPlayerStateChanged(VideoPlayer* player){
    if(player->getState() != VideoPlayer::Stopped) return;
    freeImage();
    update();
}
